import React, { Component } from 'react';
import axios from './../../axios';
import { 
	Modal,
	Form,
	Input,
	Select,
	Button,
	message,
	Card,
	Table,
	Tag,
	Pagination,
	ConfigProvider,
	Menu,
	Dropdown,
	InputNumber
} from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import zhCN from 'antd/es/locale/zh_CN';
import BaseForm from './../../components/BaseForm';
import UploadUserExcel from './../../components/UploadUserExcel';
import './index.less';
const FormItem = Form.Item;
const Option = Select.Option;

class UserManage extends Component {
	
	formRef = React.createRef();//创建用户表单
	searchFormRef = React.createRef();//搜索用户信息表单
	spaceFormRef = React.createRef();//用户空间分配表单
	roleAddFormRef = React.createRef();//用户角色添加表单
	roleDeleteFormRef = React.createRef();//用户角色删除表单
	
	state = {
		isCreateVisible: false,//创建用户模态框
		isUpdateVisible: false,//修改用户模态框
		isSpaceVisible: false,//用户空间分配模态框
		isRoleAddVisible: false,//用户角色添加模态框
		isRoleDeleteVisible: false,//用户角色删除模态框
		isRoleVisible: false,//用户角色管理，把上面两个增和删合并为这一个了
		hasRole: [],//已有角色
		dataSource: [],//列表数据
		requestParams: {//请求列表数据的参数
			field: "", 
			value: "", 
			page: 1, 
			limit: 10
		},
		pageSizeOptions:["10","20","50"],//表格显示每页多少条分页记录数
		count: 0,//列表总数
		updateFormList: [],//编辑的Form.Item数据
		selectedItem: {},//当前选中项,用于操作栏的各个操作
		roleDeleteOptions: [],//用户角色删除的Option值
	}
	
	roleAddOptions = [];//用户角色添加的选项
	
	//获取用户信息
	requestList = (data) => {
		axios.ajax({
			url: "/Manager/UserMng/userRetrieve", 
			method: "post",
			data: data,
		}).then(res=>{
			if(res.code === 0){
				let resData = res.result.data.map((item, index)=>{
					let key = index;
					return {...item, key}
				})
				this.setState({
					dataSource: resData,
					count: res.result.count
				})
			}
		}).catch(err=>{
		})
	}
	
	//查询用户信息
	searchSubmit = values => {
		let data = {...this.state.requestParams};
		if(!values.value){
			data.field = "";
			data.value = "";
		}else{
			data.field = values.field;
			data.value = values.value;
		}
		this.setState({
			requestParams: data
		})
		this.requestList(data);
	}
	
	//清空创建用户的表单
	onReset = () => {
		this.formRef.current.resetFields();
	};
	
	//提交创建用户的表单
	onFinish = values => {
		this.createUserSubmit(values);
		this.setState({isCreateVisible: false});
		this.onReset();
	}
	
	//创建用户提交
	createUserSubmit = (values) => {
		let data = {
			user_info: {
				user_name: values.user_name,
				password: values.password
			},
			role_info: values.roleid,
			count_info: {
				total_size: values.size*values.company
			}
		}
		axios.ajax({
			url: "/Manager/UserMng/userCreate",
			method: "post",
			data: data,
			headers: {"Content-Type": "application/json"}
		}).then(res=>{
			if(res.code === 0){
				message.success(res.msg);
				this.requestList(this.state.requestParams);
			}
		})
	}
	
	//分页功能，点击某页
	pageChange= (current, pageSize) => {
		let data = {...this.state.requestParams};
		data.page = current;
		data.limit = pageSize;
		this.setState({
			requestParams: data
		})
		this.requestList(data);
	}
	//分页功能，选择每页显示几个
	pageSizeChange = (current, pageSize) => {
		let data = {...this.state.requestParams};
		data.page = 1;
		data.limit = pageSize;
		this.setState({
			requestParams: data
		})
		this.requestList(data);
	}
	
	//点击修改按钮
	userUpdate = (record) => {
		let updateFormList = [
			{
				type: 'INPUT',
				label: '手机号',
				field: 'phone',
			},
			{
				type: 'INPUT',
				label: '拼音',
				field: 'pinyin',
			},
			{
				type: 'INPUT',
				label: '别名',
				field: 'nick_name',
			},
			// {
			// 	type: 'RADIO',
			// 	label: '是否锁定',
			// 	field: 'is_locked',
			// 	list: [
			// 		{value: 0, name: "解锁"},
			// 		{value: 1, name: "锁定"}
			// 	]
			// },
			{
				type: 'INPUT',
				label: '备注',
				field: 'remark',
			}
		]
		this.setState({
			isUpdateVisible: true,
			updateFormList,
			selectedItem: record
		});
	}
	
	//修改用户信息保存提交
	handleUpdateSubmit = (params) => {
		let userid = this.state.selectedItem.id;
		let data = {
			userid,
			new_data: params
		};
		this.setState({isUpdateVisible: false});
		axios.ajax({
			url: "/Manager/UserMng/userUpdate",
			method: "post",
			data: data,
			headers: {"Content-Type": "application/json"}
		}).then(res=>{
			if(res.code === 0){
				message.success(res.msg);
				this.requestList(this.state.requestParams);
			}
		})
	}
	
	//删除用户
	userDelete = record => {
		Modal.confirm({
			title: `确认删除 ${record.user_name} ？`,
			icon: <ExclamationCircleOutlined />,
			content: "想好后再操作喔",
			okText: "确认删除",
			cancelText: "取消",
			onOk:()=>{
				axios.ajax({
					url: "/Manager/UserMng/userDelete",
					method: "post",
					data: {userid: record.id}
				}).then(res=>{
					if(res.code === 0){
						message.success(res.msg);
						this.requestList(this.state.requestParams);
					}
				})
			}
		})
	}
	
	//解锁用户
	userLock = record => {
		Modal.confirm({
			title: `确认解锁 ${record.user_name} ？`,
			icon: <ExclamationCircleOutlined />,
			onOk:()=>{
				axios.ajax({
					url: "/Manager/UserMng/userUnlock",
					method: "post",
					data: {userid: record.id}
				}).then(res=>{
					if(res.code === 0){
						message.success(res.msg);
						this.requestList(this.state.requestParams);
					}
				})
			}
		})
	}
	
	//点击用户空间分配
	userSpace = record => {
		this.setState({
			selectedItem: record,
			isSpaceVisible: true
		})
	}
	//用户空间分配提交
	spaceSubmit = values => {
		let data = {
			userid: this.state.selectedItem.id,
			total_size: (values.size * values.company)
		}
		axios.ajax({
			url: "/Manager/UserMng/userSpaceUpdate",
			method: "post",
			data: data
		}).then(res=>{
			if(res.code === 0){
				message.success(res.msg);
				this.requestList(this.state.requestParams);
			}
		})
		this.setState({
			isSpaceVisible: false
		})
	}
	
	//点击用户角色管理
	userRoleEdit = record => {
		let hasRole = record.roles.map(item=>{
			return item.id
		})
		this.setState({
			selectedItem: record,
			hasRole,
			isRoleVisible: true
		})
	}
	
	//用户角色变化
	handleRoleChange = values => {
		// console.log(values);
	}
	
	//用户角色增加
	handleRoleSelect = value => {
		this.roleSubmit("/Manager/UserMng/userRoleCreate",value);
	}
	
	//用户角色删除
	handleRoleDeselect = value => {
		this.roleSubmit("/Manager/UserMng/userRoleDelete",value);
	}
	
	//角色增删操作
	roleSubmit = (url,value) =>{
		axios.ajax({
			url: url,
			method: "post",
			data: {userid: this.state.selectedItem.id, roleid: value}
		}).then(res=>{
			if(res.code === 0){
				message.success(res.msg);
				this.requestList(this.state.requestParams);
			}
		})
	}
	
	componentDidMount(){
		this.requestList(this.state.requestParams);
		//获取角色信息
		axios.ajax({
			url: "/Manager/RoleMng/roleRetrieve",
			method: "post",
			data: {field: "", value: "", page: 1, limit: 50}
		}).then(res=>{
			if(res.code === 0){
				res.result.data.map(item => {
					return this.roleAddOptions.push(
						<Option value={item.id} key={item.id}>{item.role_name}</Option>
					);
				})
			}
		}).catch(err=>{
		})
	}
	
	render(){
		const columns = [
			{
				title: '帐号',
				dataIndex: 'user_name',
				width: 100,
				fixed: 'left',
			},
			{
				title: '手机号',
				dataIndex: 'phone',
				width: 120
			},
			{
				title: '状态',
				dataIndex: 'is_locked',
				width: 80,
				render: item => {
					return item === 1 ? <Tag color="red">已锁定</Tag> : <Tag color="cyan">正常</Tag>;
				}
			},
			{
				title: '别名',
				dataIndex: 'nick_name',
				width: 100
			},
			{
				title: '所属角色',
				dataIndex: 'roles',
				render: roles => {
					return roles.map(item => {
						return item.role_name
					}).join("，");
				}
			},
			{
				title: '备注',
				dataIndex: 'remark'
			},
			{
				title: '创建时间',
				dataIndex: 'create_time',
				width: 200
			},
			{
				title: '操作',
				key: 'action',
				fixed: 'right',
				width: 220,
				render: (text, record) => {
					const menu = (
						<Menu style={{width: "100px"}}>
							<Menu.Item key="1" onClick={() => this.userLock(record)} color="#108ee9">解锁</Menu.Item>
							<Menu.Item key="2" onClick={() => this.userSpace(record)} color="#108ee9">分配空间</Menu.Item>
							<Menu.Item key="3" onClick={() => this.userRoleEdit(record)} color="#108ee9">角色管理</Menu.Item>
					    </Menu>
					);
					return record.is_del?<Tag color="red">用户已删除</Tag>:
					record.user_name === "admin"?
					<div>
						<Button type="primary" size="small" onClick={() => this.userUpdate(record)} color="#108ee9">编辑</Button>
						<Dropdown overlay={menu}>
							<Button size="small" style={{padding: "0 16px"}}>
								...
							</Button>
						</Dropdown>
					</div>
					:
					<div>
						<Button type="primary" size="small" onClick={() => this.userUpdate(record)} color="#108ee9">编辑</Button>
						<Button type="primary" size="small" onClick={() => this.userDelete(record)} color="#f45656" danger>删除</Button>
						<Dropdown overlay={menu} placement="bottomRight">
							<Button size="small" style={{padding: "0 16px"}}>
								...
							</Button>
						</Dropdown>
					</div>
				}
			}
		];
		const layout = {
		    labelCol: { span: 6 },
		    wrapperCol: { span: 18 },
		};
		const tailLayout = {
		    wrapperCol: { offset: 6, span: 18 },
		};
		const count = this.state.count;
		const current = this.state.requestParams.page;
		const pageSize = this.state.requestParams.limit;
		return (
			<div style={{padding: 20}}>
				<Card className="page-search-wrap">
					<Form layout="inline" ref={this.searchFormRef} onFinish={this.searchSubmit}>
						<FormItem
							label="查询条件"
							name="field"
						>
							<Select
								placeholder="请选择查询条件"
								allowClear
								style={{width: 150}}
							>
								<Option value="user_name">帐号</Option>
								<Option value="phone">手机号</Option>
							</Select>
						</FormItem>
						<FormItem
							label="条件值"
							name="value"
						>
						    <Input autoComplete="off" />
						</FormItem>
						<Form.Item>
							<Button type="primary" htmlType="submit">
							    查询
							</Button>
							<Button htmlType="button" onClick={()=>this.searchFormRef.current.resetFields()}>
								重置
							</Button>
						</Form.Item>
					</Form>
					<div className="float-right">
						<Button 
							type="primary"
							onClick={()=>{this.setState({isCreateVisible: true})}}
						>
							创建用户
						</Button>
						{/*导入用户和导出用户*/}
						<UploadUserExcel handleUserImportSubmit={()=>this.requestList(this.state.requestParams)} />
					</div>
				</Card>
				<Card>
					<Table
						columns={columns}
						dataSource={this.state.dataSource}
						pagination={false}
						scroll={{x: 1300}}
					/>
					<ConfigProvider locale={zhCN}>
						<Pagination
							showQuickJumper
							showSizeChanger
							current={current}
							defaultPageSize={pageSize}
							total={count}
							showTotal={total => `共 ${total} 条`}
							pageSizeOptions={this.state.pageSizeOptions}
							onChange={this.pageChange}
							onShowSizeChange={this.pageSizeChange}
						/>
					</ConfigProvider>
				</Card>
				<Modal
					title="创建用户"
					visible={this.state.isCreateVisible}
					onCancel={()=>{this.setState({isCreateVisible: false})}}
					footer={null}
				>
					<Form
						{...layout}
						ref={this.formRef}
						onFinish={this.onFinish}
					>
						<FormItem
							label="帐号"
							name="user_name"
							validateTrigger="onChange"
							rules={[
								{required: true, message: "请输入账号"},
								{min:6,max:18,message:"请输入6-18个字符"},
								{pattern: /^\w+$/g, message: "不能包含特殊字符"},
							]}
						>
						    <Input autoComplete="off" />
						</FormItem>
						<FormItem
							label="密码"
							name="password"
							validateTrigger="onChange"
							rules={[
								{required: true, message: "请输入密码"},
								{min:6,max:18,message:"请输入6-18个字符"},
								{pattern: /^[a-z0-9_]{3,16}$/, message: "不符合格式"}
							]}
						>
							<Input.Password autoComplete="off" />
						</FormItem>
						<FormItem
							label="分配空间"
							name="size"
							validateTrigger="onChange"
							rules={[
								{required: true, message: "请输入分配的空间"},
								{pattern: /^\d+$/g, message: "不能包含特殊字符"}
							]}
						>
						    <InputNumber max={1000000} maxLength={8}  style={{width: "100%"}} placeholder="请输入该用户拥有空间大小" autoComplete="off" />
						</FormItem>
						<Form.Item
							label="分配空间单位"
							name="company"
							rules={[
								{required: true, message: "请选择单位"},
							]}
						>
							<Select
								placeholder="请选择单位"
								allowClear
							>
								<Option value={1048576}>MB</Option>
								<Option value={1073741824}>GB</Option>
								<Option value={1099511627776}>TB</Option>
							</Select>
						</Form.Item>
						<FormItem
							label="分配角色"
							name="roleid"
							rules={[
								{required: true, message: "请至少选择一个角色"}
							]}
						>
						    <Select
								mode="multiple"
								placeholder="请至少选择一个角色"
							>
								{this.roleAddOptions}
							</Select>
						</FormItem>
						<Form.Item  {...tailLayout}>
							<Button type="primary" htmlType="submit">
							    保存
							</Button>
							<Button htmlType="button" onClick={this.onReset}>
								重置
							</Button>
						</Form.Item>
					</Form>
				</Modal>
				<Modal
					title="修改用户"
					visible={this.state.isUpdateVisible}
					onCancel={()=>{this.setState({isUpdateVisible: false})}}
					footer={null}
				>
					<BaseForm
						formList={this.state.updateFormList}
						selectedItem={this.state.selectedItem}
						updateSubmit={this.handleUpdateSubmit}
					/>
				</Modal>
				<Modal
					title="用户空间分配"
					visible={this.state.isSpaceVisible}
					onCancel={()=>{this.setState({isSpaceVisible: false})}}
					footer={null}
				>
					<Form
						{...layout}
						ref={this.spaceFormRef}
						onFinish={this.spaceSubmit}
					>
						<FormItem
							label="分配空间"
							name="size"
							validateTrigger="onChange"
							rules={[
								{required: true, message: "请输入分配的空间大小"},
								{pattern: /^\d+$/g, message: "不能包含特殊字符"}
							]}
						>
						    <InputNumber max={1000000} maxLength={8} style={{width: "100%"}} placeholder="请输入该用户拥有空间大小" autoComplete="off" />
						</FormItem>
						<Form.Item
							label="分配空间单位"
							name="company"
							rules={[
								{required: true, message: "请选择单位"},
							]}
						>
							<Select
								placeholder="请选择单位"
								allowClear
							>
								<Option value={1048576}>MB</Option>
								<Option value={1073741824}>GB</Option>
								<Option value={1099511627776}>TB</Option>
							</Select>
						</Form.Item>
						<Form.Item  {...tailLayout}>
							<Button type="primary" htmlType="submit">
							    保存
							</Button>
							<Button htmlType="button" onClick={()=>this.spaceFormRef.current.resetFields()}>
								重置
							</Button>
						</Form.Item>
					</Form>
				</Modal>
				<Modal
					title="用户角色管理"
					visible={this.state.isRoleVisible}
					onCancel={()=>{this.setState({isRoleVisible: false})}}
					footer={null}
				>
					<Select
						mode="multiple"
						style={{ width: '100%' }}
						defaultValue={this.state.hasRole}
						onChange={this.handleRoleChange}
						onSelect={this.handleRoleSelect}
						onDeselect={this.handleRoleDeselect}
					>
						{this.roleAddOptions}
					</Select>
				</Modal>
			</div>
		)
	}
}

export default UserManage;